from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin


# 自定义登录验证中间件
class LoginRequiredMiddleware(MiddlewareMixin):
    # 定义不需要登录验证的URL列表
    WHITELIST_URLS = [
        '/',
        '/index/',
        '/api/boss-info/',
        '/login/',
        '/logout/',
        '/register/',
        '/api/check_username/',
        '/api/check_email/',
        '/api/vue3/',
        '/api/vue3/items/',
    ]

    def __call__(self, request):
        # 获取当前请求的URL地址
        current_path = request.path

        # 检查当前URL是否不是登录页面且用户未登录，则重定向到登录页面
        if current_path not in self.WHITELIST_URLS and not request.user.is_authenticated:
            return redirect(reverse('login'))

        # 继续处理请求
        return self.get_response(request)








